package org.flowable.app.rest.listener;

import cmbchina.util.AjaxJson;
import cmbchina.util.FlowScriptRunUtils;
import cmbchina.util.RunScript;
import cmbchina.util.ScriptResult;
import cmbchina.util.common.CusTaskComonOptUtils;
import cmbchina.util.db.FlowDb;
import cmbchina.util.db.FlowFormDb;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.flowable.app.cusTaskExe.CusScriptTask;
import org.flowable.app.cusTaskExe.CusTaskOptParams;
import org.flowable.app.model.runtime.CompleteFormRepresentation;
import org.flowable.app.service.runtime.FlowableTaskFormService;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.ProcessEngines;
import org.flowable.engine.TaskService;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.task.service.delegate.DelegateTask;
import org.flowable.variable.api.persistence.entity.VariableInstance;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zm on 17-11-5.
 */
public class CusScriptTaskAutoExeListener implements TaskListener {

//    @Autowired
//    protected FlowableTaskFormService taskFormService;
//    @Autowired
//    protected TaskService taskService;
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CusScriptTaskAutoExeListener.class);

    @Override
    public void notify(DelegateTask listener) {

        logger.info("--------CusScriptTaskAutoExeListener listener---------");
        String taskDefinitionKey = listener.getTaskDefinitionKey();
        String processInstanceId = listener.getProcessInstanceId();
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        String taskId = listener.getId();
        TaskService taskService = processEngine.getTaskService();
//        Map<String,Object> map1= taskService.createTaskQuery().processInstanceId(listener.getProcessInstanceId()).singleResult().getProcessVariables();
//        Map<String,Object> map2= taskService.createTaskQuery().processInstanceId(listener.getProcessInstanceId()).singleResult().getTaskLocalVariables();
//        Map<String,Object> map3= listener.getVariables();
        AjaxJson ajaxJson = new CusTaskOptParams().optCompleteFormRepresentation(listener,taskDefinitionKey,processInstanceId);

        if(ajaxJson.isSuccess()){
            CompleteFormRepresentation completeTaskFormRepresentation = (CompleteFormRepresentation) ajaxJson.getObj();
            new CusScriptTask().exe(completeTaskFormRepresentation, taskService, taskId, listener.getDescription(),listener.getProcessInstanceId(),taskDefinitionKey);
        }
    }



}
